package com.agent.coreservice;

import java.net.ServerSocket;

public class PortUtils {	
	/**
	 * get current free port on this computer inside a range.
	 * @return a tcp port that is free or -1 if there is not a free port inside the range of number.
	 */
	public static synchronized int getFreePort(int from, int to){
		int freePort = -1;

		if (isAvaiPort(from))
			freePort = from;
		else {
			for (int p = from+1; p <= to; p++) {
				if (isAvaiPort(p)) {
					freePort = p;
					break;
				}
			}
		}
		return freePort;
	}

	/**
	 * test if a tcp port is available.
	 * 
	 * @param i
	 * @return
	 */
	public static boolean isAvaiPort(int i) {
		try {
			ServerSocket sock = new ServerSocket(i);
			sock.close();
			return true;
		} catch (java.io.IOException e) {
			return false;
		}
	}
	
}
